package com.game.ui
{
	import com.game.core.GlobalInterface;
	import com.game.core.frame.Updatable;
	
	import flash.display.Sprite;
	
	public class BaseView extends Updatable
	{
		protected var _viewID : int;
		protected var _ui : Sprite;
		protected var _visible : Boolean;
		protected var _visibleFocus : Boolean;
		protected var _x : int;
		protected var _y : int;
		
		public function BaseView(viewId:int,ui:*,visibleFocus:Boolean=true)
		{
			_visibleFocus = visibleFocus;
			_viewID = viewId;
			if(ui == null)
				ui = new Sprite();
			setUI(ui);
		}
		
		public function setUI(ui : *) : void
		{
			if(ui == null)
				return;
			
			_ui = ui;
			_ui.focusRect = null;
			_ui.cacheAsBitmap = true;
			_ui.tabEnabled = false;
			_ui.tabChildren = false;
			_ui.name = 'BaseView_' + _viewID;
			
			if(_visible)
			{
				addToDisplayObjectList();
			}
			init();
		}
		
		protected function init() : void
		{
			createChildren();
			layoutChildren();
		}
		
		/**
		 * 构建子对象
		 */
		protected function createChildren() : void
		{
		}
		
		/**
		 * 排版
		 */
		protected function layoutChildren() : void
		{
		}
		
		/**
		 * 显示到舞台
		 */		
		private function addToDisplayObjectList():void
		{
			GlobalInterface.uiContainer.addChild(_ui);
			if(_visibleFocus)
				GlobalInterface.stage.focus = _ui;
		}
		
		/**
		 * 从舞台移除
		 */		
		private function removeFromDisplayObjectList():void
		{
			if(_ui.parent)
				_ui.parent.removeChild(_ui);
			if(GlobalInterface.stage.focus == _ui)
				GlobalInterface.stage.focus = GlobalInterface.stage;
		}
		
		public function move(x : int , y : int , relativeViewId : int = 0) : void
		{
			if(_ui)
			{
				if(relativeViewId != 0)
				{
					var view:BaseView = Uimanager.getWidget(_viewID);
					if(view)
					{
						_x = view.x + x;
						_y = view.y + y;
					}
				}else
				{
					_x = x;
					_y = y;
				}
			}else
			{
				_x = x;
				_y = y;
			}
		}
		
		public function resize(stageWidth : int , stageHeight : int) : void
		{
		}
		
		public function center() : void
		{
			move((GlobalInterface.stage.stageWidth - getWidth()) / 2 , (GlobalInterface.stage.stageHeight - getHeight()) / 2);
		}
		
		public function getWidth() : int
		{
			if(_ui)
			{
				return _ui.width;
			}
			return 0;
		}
		
		
		public function getHeight() : int
		{
			if(_ui)
			{
				return _ui.height;
			}
			return 0;
		}
		
		public function get x():int
		{
			return _x;
		}
		
		public function get y():int
		{
			return _y;
		}

	}
}